var util = require('../../utils/util.js');
var api = require('../../config/api.js');

var app = getApp();

Page({
  data: {
    couponList: [],
    type: 0,
    memberUserid: ''
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;

    that.getCouponList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },
  
  getCouponList: function() {
    let that = this;
    that.setData({
      couponList: []
    });
    util.request(api.CouponLingquList).then(function(res) {
      if (res.result == 1) {
        that.setData({
          couponList: res.data
        });
      }
    });
  },

  switchTab: function(e) {
    this.setData({
      couponList: []
    });
    this.getCouponList();
  },
  //点击领取优惠券
  lingqu: function(e) {
    try {
      let that = this;
      var couponid = e.currentTarget.dataset.id;
      var coupontype = e.currentTarget.dataset.type;
      var coupons = that.data.couponList;
      let index = coupons.findIndex(v => v.id === e.currentTarget.dataset.id && v.type===coupontype);
      var choosecoupon = coupons[index];
      if (choosecoupon.type == 0) {
        util.request(api.CouponLingqu, {
          id: couponid
        }).then(function(res) {
          if (res.result == 1) {
            choosecoupon.type=1;
            wx.showToast({
              title: "领取成功",
              duration: 2000
            })
            that.setData({
              couponList: coupons
            });
          }
        });
      }
      else
      {
        wx.switchTab({
          url: '/pages/fenlei/fenlei'
        });
      }
    } catch (error) {

    }
  }
})